﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace Copia
{
    public partial class Form1 : Form
    {
        private string localDestnDir = null;

        public Form1()
        {
            InitializeComponent();
            localDestnDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\KOFAX\";
            try
            {
                foreach (string filePaths in Directory.GetFiles(localDestnDir, "*"))
                {
                    File.Delete(filePaths);
                }
            }
            catch (Exception)
            {
                                
            }            
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (!ValidarUsuario())
                return;
            panel1.Enabled = false;
            Copiar(@"C:\DIGITALIZACION\SCANNER");
            Status.Text = "Finalizado";
            Application.DoEvents();
            panel1.Enabled = true;
        }

        private void Copiar(string DirRuta)
        {

            folderBrowserDialog1.ShowDialog();
            string Archivo = "";
            string Divipol = "";

            string Ruta = folderBrowserDialog1.SelectedPath;
            if (Directory.Exists(Ruta))
            {
                Ruta += @"\E14\";

                try
                {
                    Directory.CreateDirectory(Ruta);
                    System.IO.StreamWriter file = new System.IO.StreamWriter(Ruta + "KTRL05" + Properties.Settings.Default.Prefijo + "01.TXT");
                    foreach (string filePaths in Directory.GetFiles(DirRuta))
                    {
                        Status.Text = "Copiando Imagenes";
                        Application.DoEvents();
                        Archivo = Path.GetFileName(filePaths);
                        Divipol = Archivo.Substring(2, 14) + ".tif";
                        File.Copy(filePaths, Ruta + Properties.Settings.Default.Prefijo + Divipol, true);
                        file.WriteLine(Properties.Settings.Default.Prefijo + Divipol);
                    }
                    file.Close();
                    MessageBox.Show("Finalizado");
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {            
            if (!ValidarUsuario())
                return;
            panel1.Enabled = false;
            if (!Directory.Exists(localDestnDir))
                Directory.CreateDirectory(localDestnDir);
            string[] files = GetFileList();
            if (files != null)
            {
                foreach (string file in files)
                {
                    Download(file);
                }
                Copiar(localDestnDir);
            }
            Status.Text = "Finalizado";
            Application.DoEvents();
            panel1.Enabled = true;
        }

        private bool ValidarUsuario()
        {
            bool Res = true;
            remoteDir.Text = remoteDir.Text.ToUpper();
            Res = Res && ((remoteDir.Text.Length == 4) ? true : false);
            Res = Res && ((remoteDir.Text.Substring(0, 2) == "PC") ? true : false);
            try
            {
                int.Parse(remoteDir.Text.Substring(2, 2));
            }
            catch
            {
                Res = false;
            }
            if (!Res)
            {
                MessageBox.Show("Ingrese un USUARIO valido");
            }
            return Res;
        }



        public string[] GetFileList()
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            WebResponse response = null;
            StreamReader reader = null;
            try
            {
                Status.Text = "Descargando Imagenes";
                Application.DoEvents();
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + Properties.Settings.Default.ftpServerIP + ":" + Properties.Settings.Default.ftpPort + "/" + remoteDir.Text + "/"));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(Properties.Settings.Default.ftpUserID, Properties.Settings.Default.ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                reqFTP.UsePassive = true;
                response = reqFTP.GetResponse();
                reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                // to remove the trailing '\n'
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                downloadFiles = null;
                return downloadFiles;
            }
        }

        private void Download(string file)
        {
            try
            {
                Status.Text = "Descargando Imagenes";
                Application.DoEvents();
                string uri = "ftp://" + Properties.Settings.Default.ftpServerIP + ":" + Properties.Settings.Default.ftpPort + "/" + remoteDir.Text + "/" + file;
                Uri serverUri = new Uri(uri);
                if (serverUri.Scheme != Uri.UriSchemeFtp)
                {
                    return;
                }
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + Properties.Settings.Default.ftpServerIP + ":" + Properties.Settings.Default.ftpPort + "/" + remoteDir.Text + "/" + file));
                reqFTP.Credentials = new NetworkCredential(Properties.Settings.Default.ftpUserID, Properties.Settings.Default.ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Proxy = null;
                reqFTP.UsePassive = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileStream writeStream = new FileStream(localDestnDir + "\\" + file, FileMode.Create);
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                }
                writeStream.Close();
                response.Close();
            }
            catch (WebException wEx)
            {
                MessageBox.Show(wEx.Message, "Download Error");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Download Error");
            }
        }

    }
}
